package com.edie.customview.custom;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

/**
 * edie create on 2018/10/8
 */
public class PathView extends View {
    public float currentx = 40;
    public float currenty = 50;
    public float prex;
    public float prey;
    List<Point> mPointList = new ArrayList<>();
    private Path mpath = new Path();//定义路径
    private Paint mPaint;
    private OnPathUpdateListener mListener;


    public PathView(Context context) {
        super(context);
        init();
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setColor(Color.RED);
        mPaint.setStyle(Paint.Style.STROKE);//将画笔设置为空心，才会画成曲线
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(5);//设置画笔宽度
        mPaint.setAntiAlias(true);

    }

    public PathView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PathView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        currentx = event.getX();
        currenty = event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPointList.clear();
                //先清空之前的轨迹
                mpath.reset();
                mpath.moveTo(currentx, currenty);
                prex = currentx;
                prey = currenty;
                mPointList.add(new Point((int) currentx, (int) currenty));
                break;
            case MotionEvent.ACTION_MOVE:
                mpath.quadTo(prex, prey, currentx, currenty);
                prex = currentx;
                prey = currenty;
                mPointList.add(new Point((int) currentx, (int) currenty));
                break;
            case MotionEvent.ACTION_UP:
                if (mListener != null) {
                    mListener.onPathUpdate(mPointList);
                }
                break;
        }
        invalidate();
        return true;

//        return super.onTouchEvent(event);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(500, 500, 5, mPaint);
        canvas.drawPath(mpath, mPaint);
    }

    public void setOnPathUpdateListener(OnPathUpdateListener listener) {
        mListener = listener;
    }

    public interface OnPathUpdateListener {
        void onPathUpdate(List<Point> points);
    }
}
